<template>
  <div class="add-invoice-management">
    <!-- 表单区域 -->
    <div class="form-section">
      <form @submit.prevent="handleSubmit" class="invoice-form">
        <!-- 开票单位 -->
        <div class="form-item">
          <label class="form-label required">开票单位</label>
          <input 
            v-model="formData.distributorName" 
            type="text" 
            class="form-input"
            placeholder="请输入开票单位"
            required
          />
        </div>

   

        <!-- 发票类型 -->
        <div class="form-item">
          <label class="form-label required">发票类型</label>
          <div class="radio-group">
            <label class="radio-item">
              <input 
                type="radio" 
                v-model="formData.invoiceType" 
                :value="false"
                class="radio-input"
              />
              <span class="radio-label">普通发票</span>
            </label>
            <label class="radio-item">
              <input 
                type="radio" 
                v-model="formData.invoiceType" 
                :value="true"
                class="radio-input"
              />
              <span class="radio-label">增值税发票</span>
            </label>
          </div>
        </div>

        <!-- 发票金额 -->
        <div class="form-item">
          <label class="form-label required">发票金额</label>
          <input 
            v-model="formData.invoiceAmount" 
            type="number" 
            step="0.01"
            class="form-input"
            placeholder="请输入发票金额"
            @input="calculateTaxAmount"
            required
          />
        </div>

        <!-- 税率 -->
        <div class="form-item">
          <label class="form-label required">税率</label>
          <input 
            v-model="taxRateInput" 
            type="number" 
            step="0.1"
            class="form-input"
            placeholder="请输入梯度"
            @input="updateTaxRate"
            required
          />
        </div>

        <!-- 税额 -->
        <div class="form-item">
          <label class="form-label">税额</label>
          <input 
            v-model="formData.taxAmount" 
            type="number" 
            step="0.01"
            class="form-input readonly"
            placeholder="自动计算"
            readonly
          />
        </div>

        <!-- 开票日期 -->
        <div class="form-item">
          <label class="form-label required">开票日期</label>
          <div class="date-input-wrapper">
            <input 
              v-model="formData.invoiceDate" 
              type="date" 
              class="form-input date-input"
              placeholder="请选择开票日期"
              required
            />
            <span class="calendar-icon">📅</span>
          </div>
        </div>

        <!-- 备注 -->
        <div class="form-item">
          <label class="form-label">备注</label>
          <textarea 
            v-model="formData.notes" 
            class="form-textarea"
            placeholder="请输入备注信息"
            rows="3"
          ></textarea>
        </div>

  

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">
            提交
          </button>
          <button type="button" @click="handleCancel" class="btn btn-cancel">
            取消
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { setApi } from '@/api'

// 路由实例
const router = useRouter()

// 消息提示方法
const showSuccess = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-success'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 3000)
}

const showError = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-error'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 5000)
}

const showWarning = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-warning'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 4000)
}

// 表单数据
const formData = reactive({
  distributorName: '',
  invoiceNo: '',
  invoiceType: false, // 布尔值：false=普通发票，true=增值税发票
  invoiceAmount: 0,
  taxRate: 0,
  taxAmount: 0,
  invoiceDate: '',
  notes: '',
  preparer: '',
  createdBy: '',
  lastModifiedBy: '',
  purchaseSalesInvoices:false
})

// 税率输入（百分比形式）
const taxRateInput = ref('')

// 加载状态
const loading = ref(false)

// 更新税率
const updateTaxRate = () => {
  formData.taxRate = parseFloat(taxRateInput.value) || 0
  calculateTaxAmount()
}

// 计算税额
const calculateTaxAmount = () => {
  if (formData.invoiceAmount && formData.taxRate) {
    formData.taxAmount = parseFloat((formData.invoiceAmount * formData.taxRate / 100).toFixed(2))
  } else {
    formData.taxAmount = 0
  }
}

// 方法
const handleCancel = () => {
  router.back()
}

const handleSubmit = async () => {
  try {
    loading.value = true
    
    // 验证必填字段
    if (!formData.distributorName.trim()) {
      showWarning('请输入开票单位')
      return
    }
   
    if (!formData.invoiceAmount || formData.invoiceAmount <= 0) {
      showWarning('请输入有效的发票金额')
      return
    }
    if (!taxRateInput.value) {
      showWarning('请输入税率')
      return
    }
    if (!formData.invoiceDate) {
      showWarning('请选择开票日期')
      return
    }
    
    // 准备提交数据
    const submitData = {
      distributorName: formData.distributorName,
      invoiceNo: formData.invoiceNo,
      invoiceType: formData.invoiceType,
      invoiceAmount: parseFloat(formData.invoiceAmount.toString()),
      taxRate: formData.taxRate / 100,
      taxAmount: parseFloat(formData.taxAmount.toString()),
      invoiceDate: new Date(formData.invoiceDate).toISOString(),
      notes: formData.notes,
      preparer: formData.preparer,
      createdTime: new Date().toISOString(),
      purchaseSalesInvoices: Boolean(formData.purchaseSalesInvoices),
      createdBy: formData.createdBy,
      lastModifiedBy: formData.createdBy
    }

    const response = await setApi.addInboundOutboundInvoice(submitData)

    if (response.code === 200) {
      showSuccess('发票添加成功！')
      setTimeout(() => handleCancel(), 1500)
    } else {
      showError(`添加失败: ${response.message}`)
    }
  } catch (error: any) {
    console.error('添加出错:', error)
    if (error.response) {
      showError(`添加失败: ${error.response.data.message || '服务器错误'}`)
    } else {
      showError('网络连接失败，请检查网络或联系管理员')
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时设置默认日期
onMounted(() => {
  const today = new Date().toISOString().split('T')[0]
  formData.invoiceDate = today
})
</script>

<style scoped>
.add-invoice-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

/* 表单区域样式 */
.form-section {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 600px;
}

.invoice-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 20px;
}

.form-label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
  min-width: 80px;
  text-align: right;
}

.form-label.required::after {
  content: ' *';
  color: #dc3545;
}

.form-input, .form-textarea {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  background: white;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #007bff;
}

.form-input.readonly {
  background-color: #f8f9fa;
  color: #6c757d;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

/* 单选框样式 */
.radio-group {
  display: flex;
  gap: 20px;
  flex: 1;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.radio-input {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.radio-label {
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

/* 日期输入样式 */
.date-input-wrapper {
  position: relative;
  flex: 1;
}

.date-input {
  padding-right: 40px;
}

.calendar-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
}

/* 按钮样式 */
.form-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  min-width: 100px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-primary:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.btn-cancel {
  background: white;
  color: #007bff;
  border: 1px solid #007bff;
}

.btn-cancel:hover {
  background: #f8f9fa;
}

/* Toast 消息提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  color: white;
  font-weight: 500;
  font-size: 14px;
  z-index: 9999;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 300px;
  word-wrap: break-word;
}

.toast.show {
  transform: translateX(0);
}

.toast-success {
  background: #52c41a;
}

.toast-error {
  background: #ff4d4f;
}

.toast-warning {
  background: #faad14;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-invoice-management {
    padding: 10px;
  }
  
  .form-section {
    padding: 20px;
  }
  
  .form-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .form-label {
    min-width: auto;
    text-align: left;
  }
  
  .form-input, .form-textarea {
    width: 100%;
  }
  
  .radio-group {
    width: 100%;
    justify-content: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }

  .toast {
    right: 10px;
    left: 10px;
    max-width: none;
    transform: translateY(-100%);
  }
  
  .toast.show {
    transform: translateY(0);
  }
}
</style>